﻿using PdfiumViewer;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp2.Util
{
    class PDFUtil
    {
        public List<string> getPdfImages(string inFilePath,ImageFormat format)
        {

            List<string> files = new List<string>();

            string outFilePath = AppUtil.GetAppDir() + "pdf";

            outFilePath = $"{outFilePath}\\{DateTime.Now.ToString("yyyyMMdd-HHmmss")}";
            using (var document = PdfDocument.Load(inFilePath))
            {
                var pageCount = document.PageCount;
                for (int i = 0; i < pageCount; i++)
                {
                    string outFile = $"{outFilePath}({i + 1}).{format}";
                    var dpi = 300;
                    using (var image = document.Render(i, dpi, dpi, PdfRenderFlags.CorrectFromDpi))
                    {
                        var encoder = ImageCodecInfo.GetImageEncoders()
                            .First(c => c.FormatID == format.Guid);
                        var encParams = new EncoderParameters(1);
                        encParams.Param[0] = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, 10L);

                        image.Save(outFile, encoder, encParams);

                        files.Add(outFile);
                    }
                }
            }

            return files;
            
        }
    }
}
